package cn.hx.admin.controller;

import cn.hx.admin.entity.Menu;
import cn.hx.admin.entity.Role;
import cn.hx.admin.service.MenuService;
import cn.hx.admin.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 角色信息表(Role)表控制层
 *
 * @author makejava
 * @since 2023-12-11 10:40:14
 */
@RestController
@RequestMapping("role")
public class RoleController {
    /**
     * 服务对象
     */
    @Resource
    private RoleService roleService;

    /**
     * 分页查询
     *
     * @param role 筛选条件
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<List<Role>> queryByPage(Role role) {
        return ResponseEntity.ok(this.roleService.queryByPage(role));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Role> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.roleService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param role 实体
     * @return 新增结果
     */
    @Autowired
    private MenuService menuService;
    @PostMapping
    @Transactional
    public ResponseEntity<Role> add(@RequestBody Role role) {
        Role r = this.roleService.insert(role);
        List<Integer> menuList = role.getMenuIds();
        menuList.forEach(f->{
            menuService.insertRoleMenu(r.getId(),f);
        });
        return ResponseEntity.ok(r);
    }

    /**
     * 编辑数据
     *
     * @param role 实体
     * @return 编辑结果
     */
    @PutMapping
    @Transactional
    public ResponseEntity<Role> edit(@RequestBody Role role) {
        menuService.deleteRoleMenu(role.getId());
        List<Integer> menuIds = role.getMenuIds();
        if(menuIds!=null){
            menuIds.forEach(f->{
                menuService.insertRoleMenu(role.getId(),f);
            });
        }
        return ResponseEntity.ok(this.roleService.update(role));
    }
    

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.roleService.deleteById(id));
    }

    @DeleteMapping("deleteRoleByIdsBatch")
    public ResponseEntity<Boolean> deleteRoleByIdsBatch(String ids) {
        return ResponseEntity.ok(this.roleService.deleteRoleByIdsBatch(ids));
    }


}

